<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class SendEmail extends CI_Controller {	
	public function index()
	{	
		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		$this->form_validation->set_rules('receiver', 'receiver', 'required');		
		$this->form_validation->set_message('required', '收件人不能为空');			
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('sendemailview');
		}
		else
		{
		if($this->input->post("attachementexist")=="yes")
		{
			$config['upload_path'] = 'attachement';
			$config['allowed_types'] = 'gif|jpg|png|txt';
			$config['max_size'] = '100';
			$config['max_width'] = '1024';
			$config['max_height'] = '768';
			$this->load->library('upload', $config);
			$this->upload->do_upload('attachement');
		}
		$receiver_str=$this->input->post("receiver");		
		$receiver_arr=explode(";", $receiver_str);
		array_splice($receiver_arr,count($receiver_arr)-1,1);
		$pattern="/^[0-9a-zA-Z]+@(([0-9a-zA-Z]+)[.])+[a-z]{2,4}$/i";
		foreach ($receiver_arr as $key=>$receive) {
			$first = strpos( $receive ,"<");
			$last = strrpos( $receive ,">");
//  		$result=substr($receive,$first,$last-strlen( $receive )+1);		
			$result=substr($receive,$first+1,$last-$first-1);		
			if (!preg_match($pattern,$result))
			{
				echo "收件人不符合格式";
				exit();
			}
			$receiver_arr[$key]=$result;
		}		
		$subject=$this->input->post("subject");
		$content=$this->input->post("content");
		$this->load->library('email');
		$config['protocol'] = 'smtp';
		$config['charset'] = 'gbk';
		$config['smtp_host']='smtp.126.com';
		$config['smtp_user']='caoshiquan2010@126.com';
		$config['smtp_pass']='cao1991';
		$config['mailtype'] = 'html';
		$config['validate'] = true;
		$config['priority'] = 1;
		$config['smtp_port'] = 25;
		$config['wordwrap'] = TRUE;
		$config['crlf'] = "\r\n";
		$this->email->initialize($config);
		$this->email->from('caoshiquan2010@126.com', '曹世权');
		$this->email->to($receiver_arr);
		$this->email->subject($subject);
		$this->email->message($content);
		if($this->input->post("attachementexist")=="yes")
		{
			for($i=0;$i<count($_FILES['attachement']['name']);$i++) {		
				$this->email->attach('attachement/'.$_FILES['attachement']['name'][$i]);
			}
		}
		$this->email->send();		
		}
	}	
	public function mycheckreceiver($str)
	{
		if (substr($str, -1)!=";") {
			return false;
		}
		return true;
	}
}
